package cn.com.header.core.support.json.fastjson;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author liangzhongqiu789@sina.com
 * @date 2017-05-27
 * @time 15:06
 */
public abstract class AbstractCodec implements ObjectSerializer,ObjectDeserializer {

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        JSONLexer lexer = parser.getLexer();
        if(lexer.token() == getFastMatchToken()){
            return doDeserialze(lexer,type,fieldName);
        }
        return null;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if(object == null){
            out.writeNull();
            return;
        }
        doWrite(out,object);
    }

    public abstract <T> T doDeserialze(JSONLexer lexer, Type type, Object fieldName);
    public abstract void doWrite(SerializeWriter out, Object object) throws IOException;
}
